package com.budweiser.user.service.impl;

import com.budweiser.commons.utils.PageUtil;
import com.budweiser.model.dict.Dict;
import com.budweiser.model.page.Page;
import com.budweiser.user.dao.DictDao;
import com.budweiser.user.dto.DictSelectTree;
import com.budweiser.user.dto.DictTree;
import com.budweiser.user.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("dictService")
@Transactional
public class DictServiceImpl implements DictService {
	@Autowired
	private DictDao dictDao;

	@Override
	public void save(Dict dict) {
		dict.setCreateTime(new Date());
		dict.setUpdateTime(new Date());
		if (getVildByCode(dict.getCode())) {
			throw new IllegalArgumentException("该字典编码已存在！");
		}
		dictDao.insert(dict);
	}

	public void update(Dict dict) {
		dict.setUpdateTime(new Date());
		if (!getDictByNotIdAndCode(dict.getId(), dict.getCode())) {
			throw new IllegalArgumentException("该字典编码已存在！");
		}
		dictDao.update(dict);
	}

	private boolean getDictByNotIdAndCode(Long id, String code) {
		Dict dict = dictDao.getDictByCode(code);
		if (dict != null && id != dict.getId()) {
			return false;
		}
		return true;
	}

	@Override
	public List<DictTree> findDictTree() {
		return dictDao.findDictTree();
	}

	@Override
	public Page<Dict> findDicts(Map<String, Object> params) {
		log.info("查询分页字典列表{}", params);
		int count = dictDao.count(params);
		List<Dict> dicts = Collections.emptyList();
		if (count > 0) {
			PageUtil.pageParamConver(params, true);
			dicts = dictDao.findData(params);
		}
		return new Page<Dict>(count, dicts);
	}

	@Override
	public List<DictSelectTree> getSelectDictTree() {
		log.info("查询所有字典对象构建下拉树形：");
		return dictDao.getSelectDictTree();
	}

	private boolean getVildByCode(String code) {
		Dict dict = dictDao.getDictByCode(code);
		if (dict != null) {
			return true;
		}
		return false;
	}

	@Override
	public void dateleIds(List<Long> idList) {
		dictDao.updateDeleteStatus(idList);
	}

	@Override
	public List<Dict> findDictByParentCode(String code) {
		log.info("根据父类code查询Dict集合对象：{}", code);
		return dictDao.findDictByParentCode(code);
	}

	@Override
	public Dict getDictByCode(String code) {
		return dictDao.getDictByCode(code);
	}

	@Override
	public Dict getDictByid(Long id) {
		return dictDao.getDictByid(id);
	}
}
